<?php
/**
 * 销量录入模型
 */
class salesModel extends RelationModel {

	//表单验证
	public $_validate	=	array(
		array('modelId','require','请选择机型',1,'',1),
		array('imei','require','IMEI必须填写',1,'',1),
		array('imei','require','IMEI已经存在',1,'unique',1), 
		array('imei','checkImei','IMEI格式不正确',1,'callback', 1),
	);
    
    protected $_auto = array(
        array('createTime','time',1,'function')
    );
    
    protected $_link = array(
        'store'=>array(
            'mapping_type'          =>BELONGS_TO,
            'foreign_key'=>'storeId',
            'mapping_fields'=>'name,ctms,channel,regionId',
        ),
        'model'=>array(
            'mapping_type'          =>BELONGS_TO,
            'foreign_key'=>'modelId',
            'mapping_fields'=>'name',
        ),
        'user'=>array(
            'mapping_type'          =>BELONGS_TO,
            'foreign_key'=>'userId',
            'class_name'=>'admin',
            'mapping_fields'=>'realName,userName',
        ),        
    );

	/**
	 * 较验 IMEI 格式是否正确
	 */
	public function checkImei($imei){
		if( preg_match("/^\d{15}$/",$imei)){
			return TRUE;
		}else{
			return FALSE;
		}
	}
	
	// --------------------------------------------------------------------
	
	/**
	 * 销量统计
	 * @param array $where
	 * @return array
	 */
	public function salesCount($where){
		//上报销量
		$data['total'] = D('sales')->alias('sales')->where($where)->count();
	
		//有效销量
		$trueWhere = array_merge($where, array('sales.verify'=>1));
		$data['true'] = D('sales')->alias('sales')->where($trueWhere)->count();
		
		//重点机型销量
		$importantWhere = array_merge($trueWhere, array('m.isImportant'=>1));
		$data['important'] = D('sales')->alias('sales')
				->join(C('DB_PREFIX')."model AS m ON m.id = sales.modelId")
				->where($importantWhere)->count();
		return $data;
	}
	
	/**
	 * 销量明细报表
	 * @param array $where
	 * @return array
	 */
	public function report($where){
		$field = array(
			'u.realName',
			'b.name' => 'brandName',
			'm.name' => 'modelName',
			'm.isImportant',
			'sales.imei',
		);
		$list = D('sales')->field($field)->alias('sales')
				->join(C('DB_PREFIX')."admin AS u ON u.id = sales.userId")
				->join(C('DB_PREFIX')."model AS m ON m.id = sales.modelId")
				->join(C('DB_PREFIX')."brand AS b ON b.id = m.brandId")
				->group("sales.userId, sales.modelId, sales.imei")
				->order("u.realName, b.name, m.name")
				->where($where)->select();

		return $list;
	}
}

/* End of file salesModel.class.php */